import datetime
import json

from odoo import _, api, fields, models, tools
import logging
import paho.mqtt.client as mqtt

_logger = logging.getLogger(__name__)


class InheritProductProduct(models.Model):
    _inherit = "product.product"

    meituan_category = fields.Many2one('meituan.category', '美团品类')
    report_price = fields.Float('价格(供报表使用)')
    report_cost = fields.Float('成本(供报表使用)')

    def sync_create_bom(self, days):
        c_time = (fields.Datetime.now() - datetime.timedelta(days=days)).strftime("%Y-%m-%d")
        product_ids = self.search([('categ_id.name', '=', '成品'), ('create_date', '>', c_time)])

        product_ids.create_bom()

    def create_bom(self):
        bom_obj = self.env['mrp.bom'].sudo()
        bom_line_obj = self.env['mrp.bom.line'].sudo()

        for rec in self:
            o_bom = bom_obj.search([('product_id', '=', rec.id)])

            if o_bom:
                continue

            bom_id = bom_obj.create({
                'product_id': rec.id, 'product_tmpl_id': rec.product_tmpl_id.id, 'type': 'phantom'
            })
            # 创建物料清单包装
            categ_bzh = self.categ_id.search([('name', '=', '包装')], limit=1)

            bzk_num = str(self.search_count([('categ_id', '=', categ_bzh.id)]) + 1)
            if len(bzk_num) < 5:
                bzk_num = ''.join(['0' for _ in range(5 - len(bzk_num))]) + bzk_num

            bzh_rec = self.sudo().create({
                'categ_id': categ_bzh.id, 'name': rec.display_name + '-包装', 'sale_ok': False, 'purchase_ok': False,
                'detailed_type': 'product', 'image_1920': rec.image_1920, 'default_code': 'BZK' + bzk_num
            })

            bom_line_obj.create({'bom_id': bom_id.id, 'product_id': bzh_rec.id})

    @api.model
    def update_product(self, name, vals):
        _logger.info('%s%s' % (name, vals))

        # if 'active' in vals:
        #     if vals['active']:
        #         to_update_record.action_unarchive()
        #         to_update_record.product_tmpl_id.action_unarchive()
        #     else:
        #         to_update_record.action_archive()
        #         to_update_record.product_tmpl_id.action_archive()
        #     vals.pop('active')
        if vals:
            self.env['product.product'].search([('name', '=', name)], limit=1).write(vals)

    @api.model
    def unlink_product(self, name):
        _logger.info('删除:%s' % name)
        to_unlinck_record = self.env['product.product'].search(
            [('name', '=', name), ["active", "in", [True, False]]])
        to_unlinck_record.action_archive()
        to_unlinck_record.product_tmpl_id.action_archive()

    @api.model
    def report_record(self):

        pricelist = self.env['product.pricelist'].search([('id', '=', 2)], limit=1)
        for row in self.env['product.product'].search([]):
            row.report_price = pricelist._get_product_price(row, 1)
            row.report_cost = row.standard_price

    @api.model
    def action_batch_category(self):
        if self._context.get('active_ids'):
            new_wizard = self.env['wizard.batch.category'].create(
                {'products_ids': ','.join([str(i) for i in self._context.get('active_ids')]), })
            view_id = self.env.ref('inherit_bom.view_wizard_batch_category_wizard_form').id

            return {
                'name': _('修改电商分类'),
                'type': 'ir.actions.act_window',
                'view_mode': 'form',
                'views': [(view_id, 'form')],
                'view_id': view_id,
                'res_model': 'wizard.batch.category',
                'res_id': new_wizard.id,
                'target': 'new',
                # 'context': {
                #     'default_products_ids': ','.join([str(i) for i in self._context.get('active_ids')]),
                #     'default_cates_id': self.env.ref('product.product_category_all'),
                # }

            }

    def button_to_meituan(self):
        client = mqtt.Client()
        client.username_pw_set(tools.config['mqtt_user'], tools.config['mqtt_password'])
        client.connect(tools.config['mqtt_server'], int(tools.config['mqtt_port']), 60)
        client.publish('/odoo', json.dumps(
            {
                'action': 'sync_to_meituan',
                'data': self.read(['name','list_price','default_code','id'])
            }
        ))
    def button_to_ele(self):
        client = mqtt.Client()
        client.username_pw_set(tools.config['mqtt_user'], tools.config['mqtt_password'])
        client.connect(tools.config['mqtt_server'], int(tools.config['mqtt_port']), 60)
        client.publish('/odoo', json.dumps(
            {
                'action': 'sync_to_ele',
                'data': self.read(['name','list_price','default_code','id'])
            }
        ))